package cn.itcast.mq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;


//ReturnCallback的全局配置,在RabbitTemplate产生的时候就配置一次
@Configuration
public class CommonConfig implements ApplicationContextAware/*Bean工厂通知,当Bean工厂准备好就会通知,调用setApplicationContext*/ {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取RabbitTemplate对象
        RabbitTemplate bean = applicationContext.getBean(RabbitTemplate.class);
        //配置ReturnCallback函数,这是在exchange发送消息到queue失败时的回调函数
        bean.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                //判断是否是延迟消息
                if (message.getMessageProperties().getReceivedDelay() > 0) {
                    //是一个延迟消息,忽略这个错误提示
                    return;
                }
                //打印或记录日志
                System.err.println("消息从exchange:" + exchange + "发送到队列失败,响应码:" + replyCode + ",失败原因:" + replyText + ",路由键:" + routingKey + ",消息内容:" + message);
                //如果需要可以消息重发...
            }
        });

    }
}
